package de.hsb.ai.devil.agent;

import jade.core.Agent;
import jade.domain.DFService;
import jade.domain.FIPAException;
import jade.domain.FIPAAgentManagement.DFAgentDescription;
import jade.domain.FIPAAgentManagement.ServiceDescription;

import org.apache.log4j.Logger;

import de.hsb.ai.devil.util.DevilHelper;

/**
 * AbstractDevilAgent serves abstract methods for reuse in childclasses
 */
@SuppressWarnings("serial")
public class AbstractDevilAgent extends Agent {
	
	private static final Logger logger = Logger.getLogger(AbstractDevilAgent.class);
	
	protected DevilHelper helper = DevilHelper.getInstance();
	
	private String serviceType;
	private String serviceName;
	
	public AbstractDevilAgent(String serviceName, String serviceType) {
		super();
		this.serviceType = serviceType;
		this.serviceName = serviceName;
		
		// learn the devil language
		DevilHelper.learnDevil(this);
	}

	@Override
	protected void setup() {
		super.setup();
		// Creating Service and agent description
		ServiceDescription sd = DevilHelper.createServiceTemplate();
		DFAgentDescription ad = new DFAgentDescription();
		sd.setOwnership(getName());
		sd.setType(serviceType);
		sd.setName(serviceName);
		
		ad.addServices(sd);
		
		try {
			// Register with Directory Facilitator (DF)
			DFService.register(this, ad);
		} catch (FIPAException e) {
			logger.error("register " + getLocalName(), e);
		}
	}
	/**
	 * Deregisters this agent from DF.
	 */
	@Override
	protected void takeDown() {
		try {
			DFService.deregister(this);
		} catch (FIPAException e) {
			logger.error("deregister " + getLocalName(), e);
		}
		
		super.takeDown();
	}

}